package com.journaldev.spring;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.journaldev.spring.model.UserInfo;
import com.journaldev.spring.service.UserInfoService;

@Controller
public class LoginController {
	private UserInfoService userInfoService;
	
	@Autowired(required=true)
	@Qualifier(value="userInfoService")
	public void setUserInfoService(UserInfoService userInfoService) {
		this.userInfoService = userInfoService;
	}
	
	@RequestMapping(value = {"/login"}, method = RequestMethod.GET)
	public String login(Model model) {
		return "login";
	}
	
	@RequestMapping(value = {"/login/authenticate"}, method = RequestMethod.POST)
	public String authenticateUser(HttpServletRequest request, @RequestParam("username") String userName, @RequestParam("password") String password, Model model, RedirectAttributes redirectAttrs) {
		/*
		if(result.hasErrors()) {
			model.addAttribute("message", "login errors");
			return "redirect:/login";
		}
		*/
		UserInfo user = userInfoService.authenticateUser(userName, password);
		if(user != null) {
			request.getSession().setAttribute("USER_LOGIN",user);
			return "redirect:/patients";
		} else {
			model.addAttribute("message", "login errors . User name or password incorrect");
			return "login";
		}
		
	}
}
